Android namespace总结

在Android工程中以xml为布局文件方便快速进行布局的创建,namespace在xml中是不可或缺的一部分,但是这个玩意到底是什么意思?

1
2
3
4
5
6
7
8
9
10
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />

</RelativeLayout>

首先来看一个最简单的例子,在RekativeLayout中声明了namespace:android。
它的格式是这样的:
xmlns:xxx="http://schemas.android.com/apk/yyy"
xmlns(xml namespace)表示xml命名空间。后面的xxx是这个命名空间的一个代号,方便后面使用,在=后面是一个URI,它代表这个命名空间的具体位置。
xmlns:android="http://schemas.android.com/apk/res/android"
这句声明就表示我要使用URI为http://schemas.android.com/apk/res/android的命名空间,这里面http://schemas.android.com/是Android中固定的写法,表示Android命名空间,后面的/apk/res/android表示我要使用android默认的属性值。
通过namespace可以避免多个同名attribute的冲突。
常用的几个namespace有以下三个:
(1)xmlns:android="http://schemas.android.com/apk/res/android
这个不用多说,只要做过Android开发的都知道。
(2)xmlns:tools=”http://schemas.android.com/tools
可能大家对这个tools不太熟悉。这个namespace里面的东西在我们打包生成apk时不会被加入包中,正如它的名字所示,它仅仅是Android Studio提供给我们调试使用的tools,通过它设置一些attr可以很方便的在android studio中的ui预览界面调试。
(3)xmlns:app="http://schemas.android.com/apk/res-auto"
关于这个命名空间,我查了一些资料。

The app namespace is not specific to a library, but it is used for all attributes defined in your app, whether by your code or by libraries you import, effectively making a single global namespace for custom attributes - i.e., attributes not defined by the android system.
In this case, the appcompat-v7 library uses custom attributes mirroring the android: namespace ones to support prior versions of android (for example: android:showAsAction was only added in API11, but app:showAsAction (being provided as part of your application) works on all API levels your app does) - obviously using the android:showAsAction wouldn’t work on API levels where that attribute is not defined.

可以看到这个namespace是提供给我们方便的使用自定义属性而设置的,它不针对某一个lib,而是提供给所有自定义属性使用,任何来自lib或是我们自定义的属性都可以通过这个namespace快速引用,省去再创建一个namespace。